"""
@Project:p8项目
@File:courses.py
@Author:柴奇峰
@Date:10:50
"""
from flask import Blueprint,jsonify,json
from flask_restful import Api,marshal,Resource,reqparse
from model.courses import CourseTag,Course,CourseAndTag,Category,Sections,Chapters
from model.model_filter import courseTag_fields,course_fields,chapter_fields,section_fields


courses_bp = Blueprint('courses_bp',__name__,url_prefix='/course')
api = Api(courses_bp)

class CourseTagResponse(Resource):
    def get(self):
        courseTag = CourseTag.query.all()
        data = marshal(courseTag,courseTag_fields)
        return jsonify(msg='获取成功',code=200,data=data)


class CourseResource(Resource):
    def get(self):
        parse = reqparse.RequestParser()
        parse.add_argument('free')      #免费，限免，会员
        parse.add_argument('tag_id')     #标签 id,空是全部
        parse.add_argument('online')    #0即将上线，1已上线，空全部
        parse.add_argument('sort')      #最新 空，最热2
        args = parse.parse_args()
        free = args.get('free')
        tag_id = args.get('tag_id')
        online = args.get('online')
        sort = args.get('sort')
        print('获取的',free,tag_id,online,sort,type(online))

        # 获取所有，所有标签所有课程
        if free=='' and  tag_id=='' and online=='' and sort=='':
            courses = Course.query.all()
            courses_f = marshal(courses, course_fields)
            # print('获取所有类别，所有标签,所有课程成功', courses_f)
            return jsonify(code=200, msg='获取所有类别,所有标签,所有课程成功',data=courses_f)

        # 获取所有类别(是否免费)的所有课程
        # if free and not all([tag_id,online,sort]):
        if free and tag_id=='' and online=='' and sort=='':
            # 课程表
            course = Course.query.filter_by(course_type=free).all()
            data = marshal(course,course_fields)
            return jsonify(code=200, msg='获取所有课程获取成功', data=data)

        # 类别, 单个标签，课程的全部
        # if all([free,tag_id]) and not all([online,sort]):
        if free and tag_id and online == '' and sort == '':
            courst_tag = CourseTag.query.filter_by(id=int(tag_id)).first()
            print('BBBB', courst_tag)
            list1 = []
            for i in courst_tag.course:
                if i.course_type == free:
                    coures_tag_f = marshal(i, course_fields)
                    list1.append(coures_tag_f)
            print('获取所有类别，单个标签的所有课程成功', list1)
            return jsonify(code=200, msg='获取成功', data=list1)
        # 类别 标签 是否上线
        if free and tag_id and online and sort == '':
            courst_tag = CourseTag.query.filter_by(id=int(tag_id)).first()
            list1 = []
            for i in courst_tag.course:

                if i.course_type == free and i.course_status == int(online):
                    coures_tag_f = marshal(i, course_fields)
                    list1.append(coures_tag_f)
            print('获取所有类别，单个标签的所有课程成功', list1)
            return jsonify(code=200, msg='获取成功', data=list1)
        # 标签
        if tag_id and free == ''and online == '' and sort =='':
            course = CourseAndTag.query.filter_by(tag_id=int(tag_id)).all()
            list1 =[]
            for i in course:
                couse = Course.query.filter_by(id=i.course_id).first()
                data = marshal(couse,course_fields)
                list1.append(data)
            return jsonify(code=200, msg='获取单个标签的所有课程成功', data=list1)

        # 类别 是否上线
        if free and online and tag_id == '' and sort == '':
            course = Course.query.filter_by(course_type=free).all()
            list1 = []
            for i in course:
                if i.course_status == int(online):
                    data = marshal(i,course_fields)
                    list1.append(data)
            return jsonify(code=200,msg='获取成功',data=list1)

        # 是否上线
        if online and free == '' and tag_id == '' and sort == '':
            course = Course.query.filter_by(course_status = int(online)).all()
            data = marshal(course,course_fields)
            return jsonify(msg='获取成功',code=200,data=data)

    # 获取全部课程
    # def get(self):
    #     try:
    #         parser = reqparse.RequestParser()
    #         parser = parser.add_argument('tag_id')
    #         parser = parser.add_argument('free')
    #         parser = parser.add_argument('online')
    #         parser = parser.add_argument('sort')
    #         args = parser.parse_args()
    #         tag_id = args.get('tag_id')
    #         course_types = args.get('free')
    #         course_sort = args.get("sort")
    #         course_oline = args.get("online")
    #         print("tag_id的值%s, course_types的值%s, course_sort的值%s,course_oline的值%s" % (
    #         tag_id, course_types, course_sort, course_oline))
    #
    #         # 获取所有的课程id和标签id
    #         course_and_tag = CourseAndTag.query.all()
    #         # 如果选择标签判断
    #         if tag_id:
    #             course_and_tag = CourseAndTag.query.filter_by(tag_id=int(tag_id)).all()
    #
    #         # 没有选择标签
    #         course_list = []
    #         for i in course_and_tag:
    #             course = Course.query.filter_by(id=i.course_id).first()
    #
    #             """把不满足条件的跳过"""
    #             # 判断类型，如果类型正确就执行下面的代码
    #             # continue 跳过
    #             if course_types:
    #                 if course_types != course.course_type:
    #                     continue
    #             # 判断是否上线
    #             if course_oline:
    #                 if int(course_oline) != course.course_status:
    #                     continue
    #
    #             course_data = marshal(course, course_fields)
    #
    #             course_list.append(course_data)
    #         return jsonify(message="获取课程成功", data=course_list)
    #
    #
    #     except Exception as e:
    #         print(e)
    #         return jsonify(message="获取课程失败", code=500)


class CourseinfoResource(Resource):
    def get(self):
        try:
            parse = reqparse.RequestParser()
            parse = parse.add_argument("cid")
            args = parse.parse_args()

            cid = args.get("cid")
            print('前端传的id',cid,type(cid))
            course = Course.query.filter_by(id=cid).first()
            print('bbb',course)
            chapter_course = Chapters.query.filter_by(course = cid).all()
            print('课程信息',chapter_course)
            course = marshal(course, course_fields)
            chapter_course = marshal(chapter_course, chapter_fields)
            chapter_course = json.loads(json.dumps(chapter_course))
            for i in chapter_course:
                section = Sections.query.filter_by(course=i["id"]).all()
                section = marshal(section,section_fields)
                i["section_list"] = section

            return jsonify(message="ok！",code=200, course=course, chapter=chapter_course)
        except Exception as e:
            print('错误信息',e)
            return jsonify(message="服务器错误！", code=500)

# 课程小节详细信息
class SectionInfoResource(Resource):
    def get(self):
        try:
            parse = reqparse.RequestParser()
            parse = parse.add_argument("sid")
            args = parse.parse_args()

            sid = args.get("sid")

            section = Sections.query.filter_by(id=sid).first()
            section = marshal(section,section_fields)

            return jsonify(message="ok！", code=200, data=section)
        except Exception as e:
            print(e)
            return jsonify(message="服务器错误！", code=500)



api.add_resource(CourseTagResponse,'/get_tag')# 课程标签
api.add_resource(CourseResource,'/get_course')# 所有课程
api.add_resource(CourseinfoResource,'/courseinfo')# 课程的详情
api.add_resource(SectionInfoResource, "/sectionvideo") # 课程小节详细信息




